﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Cryptography;
using System.Text;
using LKVMLMADMIN.Models;
using LKVMLMLib;
using LKVMLMADMIN.Common;
using System.Configuration;
using PinService.Lib;
using LKVService;
using System.IO;
namespace LKVMLMADMIN.Controllers.Json
{
    public class JsonTransactionController : BaseController
    {
        public Transaction transaction = new Transaction();
        public ProfitService pf = new ProfitService();
        public ActionResult GetWallets(int UserId)
        {            
            //var wallet = new Wallet();            
            var result = transaction.getWallet(UserId);
            return Json(result);
        }
        public ActionResult GetWalletsHistory(int UserId, int WalletId)
        {
            //var wallet = new Wallet();            
            var result = transaction.getWalletsHistory(UserId, WalletId);            
            return Json(result);
        }
        public ActionResult ListWallet()
        {
            //var wallet = new Wallet();            
            var result = transaction.listWallet();
            return Json(result);
        }
        public ActionResult WalletsNotPeddingWallet(int UserId)
        {
            try
            {
                var list = new List<int>(new int[] { 1, 2, 3, 4 });
                var result = transaction.WalletIn(list, UserId);
                return Json(new { Status = true, Messeger = "", Result = result });
            }
            catch (Exception ex)
            {                
                return Json(new { Status = false, Messeger = "", Result = ex.Message });                
            }
        }
        public ActionResult WalletsNotPeddingWalletUser(int UserId)
        {
            try
            {
                var list = new List<int>(new int[] { 1, 2, 3, 4 });
                var result = transaction.WalletIn(list, UserId);
                return Json(new { Status = true, Messeger = "", Result = result });
            }
            catch (Exception ex)
            {
                return Json(new { Status = false, Messeger = "", Result = ex.Message });
            }
        }
        public ActionResult WalletsNotFundingWalletUser(int UserId)
        {
            try
            {
                var list = new List<int>(new int[] { 1,2, 3, 4 });
                var result = transaction.WalletIn(list, UserId);
                return Json(new { Status = true, Messeger = "", Result = result });
            }
            catch (Exception ex)
            {
                return Json(new { Status = false, Messeger = "", Result = ex.Message });
            }
        }
        public ActionResult WalletsForBuyPack(int UserId)
        {
            try
            {
                var list = new List<int>(new int[] { 1 });
                var result = transaction.WalletIn(list, UserId);
                return Json(new { Status = true, Messeger = "", Result = result });
            }
            catch (Exception ex)
            {
                return Json(new { Status = false, Messeger = "", Result = ex.Message });
            }
        }
        public ActionResult GetListAmountBitcoin()
        {
            try {
                var list = new List<int>();
                list.Add(380);
                list.Add(760);
                list.Add(1520);
                list.Add(3040);
                list.Add(6080);
                list.Add(12160);
                return Json(new { Status = true, Messeger = "", Result = list });
            }
            catch (Exception ex)
            {
                return Json(new { Status = false, Messeger = "", Result = ex.Message });
            }
        }
        public ActionResult GetDashboard()
        {
            if (Session["UserByToken"]!=null)
            {
                UserProfile user = (UserProfile)Session["UserByToken"];
                var result = transaction.getDashboard(user.UserId);
                return Json(result);
            }
            else
            {                
                return Json("Error not user login");
            }                       
            
        }
        public ActionResult GetManagerPack(int UserId)
        {            
            try
            {
                var db = new LKVService.OrderService();
                var transactionDB = new LKVService.Transaction();
                var ROI = db.GetGConfig().ROI.Value;
                //var data = db.getListPackageByUserId(UserId);                
                var date = DateTime.Today.Date;
                var yesterday = DateTime.Today.AddDays(-1).Date;
                var totalProfit = transactionDB.getTotalCommission(UserId).Value;
                var totalOrder = db.GetOrderByUserID(UserId);
                //var TotalRemain = (totalOrder*ROI)/100 - totalProfit;
                var ProfitYesterday= db.ProfitForDate(UserId, yesterday);
                var ProfitToday = db.ProfitForDate(UserId, date);
                var ListView = new List<LKVService.StatisticList>() { 
                        new LKVService.StatisticList {Id=1,Name="Profit Today", Total=ProfitToday>0?ProfitToday.ToString("0.00"):"0", Link="#" },
                        new LKVService.StatisticList {Id=2,Name="Profit Yesterday", Total=ProfitYesterday>0?ProfitYesterday.ToString("0.00"):"0", Link="#" },
                        new LKVService.StatisticList {Id=3,Name="Total Profits", Total=totalProfit>0?totalProfit.ToString("0.00"):"0", Link="#" },
                        //new LKVService.StatisticList {Id=4,Name="Total Remain", Total=TotalRemain>0?TotalRemain.ToString("0.00"):"0", Link="#" },
                        new LKVService.StatisticList {Id=5,Name="Total Invest", Total=totalOrder.ToString(), Link="#" },             
                        //new LKVService.StatisticList {Id=6,Name="Total Pack Running", Total=transaction.getTotalRunningPackByUserID(UserId,ROI).ToString(), Link="#" },             
                        //new LKVService.StatisticList {Id=7,Name="Total Pack Expires", Total=transaction.getTotalExpiredPackByUserID(UserId,ROI).ToString(), Link="#" },             
                };
                return Json(new { Result = ListView, Status = true, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }            
        }
        public ActionResult GetRunningPack(int UserId)
        {
            LKVService.OrderService OrderServiceDB = new LKVService.OrderService();
            var gConfig = OrderServiceDB.GetGConfig();
            var result = transaction.getRunningPackByUserID(UserId, gConfig.ROI.Value);
            return Json(result);
        }
        public ActionResult GetExpiresPack(int UserId)
        {
            LKVService.OrderService OrderServiceDB= new LKVService.OrderService();            
            var gConfig=OrderServiceDB.GetGConfig();
            var result = transaction.getExpiresPackByUserID(UserId, gConfig.ROI.Value);
            return Json(result);
        }
        public ActionResult GetPackDetail(int Id)
        { 
            try
            {
                var db = new LKVService.OrderService();
                Order data = db.getOrder(Id);
                var order = new OrderView();                
                order.Id = data.ID_Order;
                order.Price = data.Amount.Value;
                order.BuyDate = data.Date.Value.ToString("MM/dd/yyyy");
                order.Profit = Convert.ToDouble( data.Percent.Value)/100 * data.Amount.Value;
                order.Remain = (db.GetGConfig().ROI.Value - data.Percent.Value) * data.Amount.Value / 100;
                order.History = db.getProfitsByOrder(data.ID);
                return Json(new { Result = order, Status = true, Messeger = "" });
            }
            catch (Exception ex)
            {
                
                return Json(new { Status = false, Messeger = ex.Message });
            }  
        }    
        public ActionResult GetPaymentMethod()
        {
            try
            {
                List<PaymentMethod> result = transaction.GetPaymentMethods();
                if (result != null)
                {
                    return Json(new { Result = result, Status = true, Messeger = "" });
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex });                
            }
        }
        public ActionResult getAccountPerfectMoney(int UserID)
        {
            try
            {        
                var PrefectAccount = transaction.getAccountPerfectMoney(UserID);
                if(PrefectAccount!=null){
                    PrefectAccount.Payer = PrefectAccount.Payer.Replace("u", "U");
                }                

                if (PrefectAccount!=null)
                {
                    return Json(new { Result = PrefectAccount, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getPerfectTransaction(int id)
        {
            try
            {
                var PrefectAccount = transaction.getPerfectMoneyTransaction(id);
                if (PrefectAccount != null)
                {
                    return Json(new { Result = PrefectAccount, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getPerfectTransaction4Wweb(int id)
        {
            try
            {
                var PrefectAccount = transaction.getPerfectMoneyTransaction4Web(id);
                if (PrefectAccount != null)
                {
                    return Json(new { Result = PrefectAccount, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getListNews()
        {
            try
            {
                var system = new LKVService.SystemService();
                var ListNews = system.getIntroListNews(null, 0);
                if (ListNews != null)
                {
                    return Json(new { Result = ListNews.Item2, Status = true, Messeger = "" });
                }

                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getNewsDetail(int Id)
        {
            try
            {
                var system = new LKVService.SystemService();
                var News = system.getNewsDetail(Id);
                if (News != null)
                {
                    return Json(new { Result = News, Status = true, Messeger = "" });
                }

                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public JsonResult BankCashout(int userid, float amount, int payment, int walletId)
        {
            var system = new LKVService.SystemService();
            var transactionService = new LKVService.Transaction();
            var withdraw = system.addWithDrawal(userid, amount, payment, walletId);
            if (withdraw != null)
            {
                return Json(new { Status = true, Messeger = "Successful" });
            }
            else
                return Json(new { Status = false, Messeger = "Unsuccessful" });
        }
        public ActionResult getBuysShare(int UserId)
        {
            try
            {
                var ListBuy = transaction.GetSharesByType(UserId,1);
                List<int> ChartLabel = new List<int>();
                List<double> ChartDataItem = new List<double>();  
                List<double[]> ChartData = new List<double[]>();                
                var now = DateTime.Now;
                var kq = transaction.ChartBuy(now);                
                foreach(dynamic item in kq){                    
                    ChartLabel.Add(item.GetType().GetProperty("label").GetValue(item, null));
                    ChartDataItem.Add(item.GetType().GetProperty("value").GetValue(item, null));                    
                }
                ChartData.Add(ChartDataItem.ToArray());

                if (ListBuy != null)
                {
                    return Json(new { Result = ListBuy, Status = true, Messeger = "", ChartLabel = ChartLabel.ToArray(), ChartData = ChartData.ToArray() });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getSellsShare(int UserId)
        {
            try
            {
                var ListSell = transaction.GetSharesByType(UserId,0);
                List<int> ChartLabel = new List<int>();
                List<double> ChartDataItem = new List<double>();
                List<double[]> ChartData = new List<double[]>();
                var now = DateTime.Now;
                var kq = transaction.ChartBuy(now);
                foreach (dynamic item in kq)
                {
                    ChartLabel.Add(item.GetType().GetProperty("label").GetValue(item, null));
                    ChartDataItem.Add(item.GetType().GetProperty("value").GetValue(item, null));
                }
                ChartData.Add(ChartDataItem.ToArray());
                if (ListSell != null)
                {
                    return Json(new { Result = ListSell, Status = true, Messeger = "", ChartLabel = ChartLabel.ToArray(), ChartData = ChartData.ToArray() });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getShareManager(int UserId)
        {
            try
            {
                var ListShare = transaction.GetPlaceOrder(UserId);
                if (ListShare != null)
                {
                    return Json(new { Result = ListShare, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult addShare(PlaceOrder Share, int WalletId)
        {
            try
            {
                //validation Share
                if (Share.UnitPrice>0 && Share.Quantity>0)
                {
                    //lay so co phieu hien co cua user
                    var balance = transaction.getBalanceShare(Share.UserId);
                    int isUpdate = 0;
                    //Sell Ban ra
                    if (Share.Type == 1)
                    {
                        if (balance >= Share.Quantity && Share.Quantity > 0)
                        {
                            isUpdate = transaction.UpdateShare(Share);
                        }
                    }
                    else
                    {
                        Share.WalletId = WalletId;
                        isUpdate = transaction.UpdateShare(Share);                        
                        double price = Share.UnitPrice*Share.Quantity;
                        transaction.chargeFormWallet(Share.UserId, WalletId, -1*price, "Buy Share");
                        //tru tien
                    }
                    if (isUpdate > 0)
                    {
                        return Json(new { Result = "", Status = true, Messeger = "Add Share Sucessful" });
                    }
                    return Json(new { Result = "", Status = false, Messeger = "Add Share unsucessful. Balance Share Not enough Or Price less 0" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Add Share unsucessful. UnitPrice or Quantity not less 0" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult UpdateShare(PlaceOrder Share)
        {
            try
            {
                
                int isUpdate = transaction.UpdateShare(Share);
                if (isUpdate > 0)
                {
                    return Json(new { Result = "", Status = true, Messeger = "Update share unsucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Update Share unsucessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getShare(int ShareId)
        {
            try
            {
                var Share = transaction.GetShare(ShareId);
                if (Share !=null)
                {
                    return Json(new { Result = Share, Status = true, Messeger = "Update share unsucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Update Share unsucessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <param name="ShareId"></param>
        /// <returns></returns>
        public ActionResult deleteShare(int ShareId)
        {
            try
            {
                var shareItem = transaction.GetShare(ShareId);
                if (shareItem!=null)
                {
                    var Share = transaction.deleteShare(ShareId);
                    //tra tien balance Share Table
                    if (Share)
                    {
                        return Json(new { Result = Share, Status = true, Messeger = "Delete share sucessful" });
                    }
                    return Json(new { Result = "", Status = false, Messeger = "Delete Share unsucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Item Share" });

            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult BuyShare(int WalletId, int Amount,int UserId)
        {
            try
            {             
                var shareItem = transaction.buyShare(UserId, WalletId, Amount);
                if (shareItem)
                {
                    return Json(new { Result = "", Status = true, Messeger = "Buy Share sucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Buy Share Unsucessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult SellShare(int Amount, int UserId)
        {
            try
            {
                var shareItem = transaction.SellShare(UserId, Amount);                
                if (shareItem)
                {
                    return Json(new { Result = "", Status = true, Messeger = "Buy Share sucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Buy Share Unsucessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getShareTransaction(int UserId)
        {
            try
            {
                var shareTransaction = transaction.GetShareTransactionByUser(UserId);
                if (shareTransaction!=null)
                {
                    return Json(new { Result = shareTransaction, Status = true, Messeger = "Buy Share sucessful" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Buy Share Unsucessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getListWithDraw(int UserId)
        {
            try
            {
                var withdraws = transaction.getListWithDrawByUser(UserId, 0);
                if (withdraws != null)
                {
                    return Json(new { Result = withdraws, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getListWithDrawCompleted(int UserId)
        {
            try
            {
                var withdraws = transaction.getListWithDrawByUser(UserId, 1);
                if (withdraws != null)
                {
                    return Json(new { Result = withdraws, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult webcallback()
        {
            string domain = DuAnDaCapEntities.getDomain();
            if (domain == "localhost")
                domain = "http://localhost:1284";
            else domain = "http://members.links.fund";

            var stringhelper = new StringHelper();
            var transaction = new LKVService.Transaction();
            var UserDB = new LKVService.User();
            var transactionid = 0;
            //ViewBag.Result = "Payment Unsuccessful";
            ViewBag.Result = "Add fund successful, please close app and open again";
            //BitConverter.ToString()
            if (Request.Form != null)
            {
                var v2_hash = Request.Form["V2_HASH"];
                string ALTERNATE_PHRASE = ConfigurationManager.AppSettings["ALTERNATE_PHRASE"].ToString();
                string ALTERNATE_PHRASE_HASH = stringhelper.MD5Hash(ALTERNATE_PHRASE).ToUpper();
                string str =
                          Request.Form["PAYMENT_ID"] + ':' + Request.Form["PAYEE_ACCOUNT"] + ':' +
                          Request.Form["PAYMENT_AMOUNT"] + ':' + Request.Form["PAYMENT_UNITS"] + ':' +
                          Request.Form["PAYMENT_BATCH_NUM"] + ':' +
                          Request.Form["PAYER_ACCOUNT"] + ':' + ALTERNATE_PHRASE_HASH + ':' +
                          Request.Form["TIMESTAMPGMT"];
                var hash = stringhelper.MD5Hash(str).ToUpper();
                if (hash == v2_hash)
                {
                    //var requestTransaction = new LKVService.formPerfectTransaction();
                    var requestTransaction = transaction.getPerfectMoneyTransaction(int.Parse(Request.Form["PAYMENT_ID"]));
                    if (requestTransaction.V2_Hash == null)
                    {
                        //thanh cong
                        //chuyen tien vao vi                                        
                        var perfectTransaction = transaction.getPerfectMoneyTransaction(requestTransaction.Id);

                        //luu lich su giao dich
                        transaction.chargeFormWallet(perfectTransaction.UserId, 1, perfectTransaction.Payment_Amount, "Add fund with batch no " + Request.Form["PAYMENT_BATCH_NUM"], Request.Form["PAYMENT_BATCH_NUM"], 1);
                        //cap nhat lai transaction Perfect Money
                        requestTransaction.Payment_Batch_Num = Request.Form["PAYMENT_BATCH_NUM"];
                        requestTransaction.Payer_Account = Request.Form["PAYER_ACCOUNT"];
                        requestTransaction.TimeStampgmt = Request.Form["TIMESTAMPGMT"];
                        requestTransaction.V2_Hash = v2_hash;
                        requestTransaction.Payment_Amount = double.Parse(Request.Form["PAYMENT_AMOUNT"]);
                        //get transaction id
                        transactionid = transaction.UpdatePerfectMoneyTransaction(requestTransaction);
                        var AccountPerfectMoney = transaction.getAccountPerfectMoney(requestTransaction.UserId);
                        //luu lai tai khoan perfecmoney
                        if (AccountPerfectMoney == null)
                        {
                            UserDB.UpdatePerfectMoney(requestTransaction.UserId, "USD", requestTransaction.Payer_Account, requestTransaction.Payer_Account, requestTransaction.Payee_Name);
                        }
                        ViewBag.Result = "Add fund successful, please close app and open again";
                        transaction.AfterAddFund(requestTransaction.UserId, requestTransaction.Payment_Amount, requestTransaction.Order_Num, DateTime.Now, 1);
                        return Redirect(domain + "/#/app/perfectmoney/1");
                        // 1 thanh cong
                    }
                    return Redirect(domain + "/#/app/perfectmoney/-1"); // store database not successful
                    
                }
                else return Redirect(domain + "/#/app/perfectmoney/-2");// Hash invalid
            }
            else return Redirect(domain + "#/app/perfectmoney/-3"); // form invalid
        }
        public ActionResult getFeeConfig()
        {
            try
            {
                User userContext = new User();
                var FeeConfig = userContext.getFeeConfig();
                if (FeeConfig!=null)
                {
                    return Json(new { Result = FeeConfig, Status = false, Messeger = "" });
                }

                return Json(new { Result = "", Status = false, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getUserReceiveWithRandom()
        {
            var db = new LKVService.User();
            var listUser = db.getListUserByGroup(4, "").ToList();
            Random r = new Random();
            
            var userGet = listUser[r.Next(listUser.Count)];
            var btAddress = "";
            return Json(new { UserName = userGet.UserName, FullName = userGet.HOTEN, Address = btAddress });
        }
        public ActionResult getListCashOutByUser(int UserID)
        {
            if (UserID > 0)
            {
                var db = new LKVService.User();
                var list = db.getListWithdrawals().Where(w => w.UserId == UserID).ToList();
                if(list.Count > 0)
                { 
                    var _kq = list.Select(s => new CashOutView
                        { 
                        Id = s.Id,
                        Amount = s.Amout,
                        Code = s.Code,
                        CreateDate = s.Create_Date != null ? s.Create_Date.Value.Date.ToString("dd/MM/yyyy") : null,
                        Payment_Method = s.Payment_Method,
                        UserId = s.UserId,
                        WalletId = s.WalletId,
                        Status = s.Status != null && s.Status.Value == 0 ? "Pending" : s.Status != null && s.Status.Value == 1 ? "Approve" : "Cancel",
                        IsConfirm = s.IsConfirm == null || s.IsConfirm.Value == false ? false : true,
                        From_User = s.From_User != null ? s.From_User.Value : 0,
                        From_UserName = db.findUserById(s.From_User != null ? s.From_User.Value : 0) != null ? db.findUserById(s.From_User != null ? s.From_User.Value : 0).UserName : null
                    }).ToList();
                    return Json(new { Status = true, Messeger = "Load Provide Room Successful", Result = _kq }, JsonRequestBehavior.AllowGet);
                }else
                    return Json(new { Status = false, Messeger = "No data", Result = "" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Status = false, Messeger = "You didn't user in system.", Result = "" }, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult getOnlyWalletByUser(int UserID)
        {
            if (UserID > 0)
            {
                var db = new LKVService.Transaction();
                var wl = db.getWalletDetail(UserID,1);
                return Json(new { Status = true, Messeger = "Load your wallet Successful", wallet = wl }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Status = false, Messeger = "You didn't user in system.", Result = "" }, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult getTransactionByWithdraw(int wdID = 0)
        {
            if (wdID > 0)
            {
                var ts = new LKVService.Transaction();
                var db = new LKVService.User();
                var wd = ts.findWithDrawById(wdID);
                if(wd != null)
                {
                    var fromUserName = db.findUserById(wd.From_User.Value) != null ?  db.findUserById(wd.From_User.Value).UserName : "";
                    return Json(new { Status = true, Messeger = "Load your wallet Successful", CreateDate = wd.Create_Date.Value.ToString("dd/MM/yyyy"), FromUser = fromUserName, Code = wd.Code }, JsonRequestBehavior.AllowGet);
                }else
                     return Json(new { Status = false, Messeger = "Load faild", Result = "" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Status = false, Messeger = "You didn't user in system.", Result = "" }, JsonRequestBehavior.AllowGet);
            }          
        }
        public ActionResult getListPackage()
        {
            var od = new LKVService.OrderService();
            var list = od.getListPackage();
            var packs = list.Select(s => new PackageView
            {
                Name = s.PackageName,
                Amount = s.Price != null ? s.Price.Value : 0
            }).ToList();
            return Json(new { Status = true, Result = packs });
        }
        public ActionResult addOrderNotProfit(int UserId = 0, double Amount = 0, string PinCode = "")
        {
            if (UserId > 0)
            {
                if (Amount > 0)
                {
                    if (!String.IsNullOrEmpty(PinCode))
                    {
                        var od = new LKVService.OrderService();
                        var db = new LKVService.User();
                        var pin = new MaThePaymentService();
                        var checkpin = pin.findMaTheBySeri(PinCode);
                        string IdOrder = generateIdOrder();
                        float _amount = (float)Amount;
                        if (checkpin != null)
                        {
                            if (checkpin.Used == null || checkpin.Used.Value == false)
                            { 
                                // kiểm tra số lượng F1 và số lượng gói active trong tháng
                                bool checkOrder = false;
                                var slf1 = db.getListByParent(UserId).ToList().Count;
                                var slOrderOfUser = od.getListOrderByUserId(UserId).Where(w=>w.Date.Value.Year==DateTime.Now.Year && w.Date.Value.Month== DateTime.Now.Month).ToList();
                                var gioiHanGoiActive = od.getAllGioiHanGoiActive().OrderByDescending(w=>w.Id).ToList();
                                if (gioiHanGoiActive.Find(w => w.SoLuongF1 == slf1) != null)
                                    if (slOrderOfUser.Count < gioiHanGoiActive.Find(w => w.SoLuongF1 == slf1).SoLuongGoiKichHoat)
                                        checkOrder = true;
                                if (checkOrder)
                                {
                                    var isOrder = od.addOrder(0, UserId, _amount, 0, IdOrder, DateTime.Now, false, false, 1, 0, "", 1);
                                    if (isOrder == true)
                                    {
                                        pin.usePinById(checkpin.ID);
                                        var order = od.findOrderbyIDOrder(IdOrder);
                                        if (order != null)
                                            od.addWaitingProvideRoom(UserId, order.ID); //them vao WaitingProvideRoom
                                    }
                                }
                                else
                                    return Json(new { Status = false, Msg = "The number of Order exceeds the allowed limit! " }, JsonRequestBehavior.AllowGet);
                            }else
                                return Json(new { Status = false, Msg = "PinCode was used" }, JsonRequestBehavior.AllowGet);
                        }else
                            return Json(new { Status = false, Msg = "PinCode is not exists." }, JsonRequestBehavior.AllowGet);
                    }else
                        return Json(new { Status = false, Msg = "PinCode is required." }, JsonRequestBehavior.AllowGet);
                }
                else
                { 
                  return Json(new { Status = false, Msg = "Amount must > 0" }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { Status = true, Msg = "Success" }, JsonRequestBehavior.AllowGet); 
            }
            else
                return Json(new { Status = false, Msg = "You didn't user in system." }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult getListOrderByUser(int UserId = 0)
        {
            if (UserId > 0)
            {
                var od = new LKVService.OrderService();
                var list = od.getListOrderByUserId(UserId).Select(s => new { 
                    Id_Order = s.ID_Order,
                    Id = s.ID,
                    Status = s.Action != null ? s.Action.Value : false,
                    Time = (s.Date.Value.AddHours(48) - DateTime.Now).TotalHours > 0 ? Convert.ToInt32((s.Date.Value.AddHours(48) - DateTime.Now).TotalHours) : 0,
                    Date = s.Date.Value.ToString("dd/MM/yyyy"),
                    Amount = s.Amount,                       
                }).OrderByDescending(w=>w.Date).ToList();
                return Json(new { Status = true, Result = list, Msg = "Success" });
            }
            else
                return Json(new { Status = false, Result = "", Msg = "You didn't user in system." });
        }
        public ActionResult getOrderById(string orderId = "")
        {
            if (!String.IsNullOrEmpty(orderId))
            {
                var od = new LKVService.OrderService();
                var order = od.findOrderbyIDOrder(orderId);
                if(order == null)
                    return Json(new { Status = false, Result = "", Msg = "Order not found" });
                return Json(new { Status = true, Result = order, Msg = "Success" });
            }
            else
                return Json(new { Status = false, Result = "", Msg = "You didn't user in system." });
        }
        public ActionResult getWalletHistoryByUser(int UserId = 0, int WalletId = 0)
        {
            if (UserId > 0)
            {
                if(WalletId == 0)
                    return Json(new { Status = false, Result = "", Msg = "Wallet not exists" });

                var db = new LKVService.Transaction();
                var list = db.getWalletsHistory(UserId, WalletId);
                return Json(new { Status = true, Result = list, Msg = "Success" });
            }
            else
                return Json(new { Status = false, Result = "", Msg = "You didn't user in system." });
        }
        public string generateIdOrder()
        {
            var od = new LKVService.OrderService();
            var countOd = od.getListOrder().Count();
            string idorder = string.Empty;
            if(countOd == 0)
                return Extension.HtmlHelperExtensions.generateRandomString(10, 1);
            for (int i = 0; i < countOd; i++)
            {
                idorder = Extension.HtmlHelperExtensions.generateRandomString(10, 1);
                var _kq = od.findOrderbyIDOrder(idorder);
                if (_kq == null)
                    break;
            }
            return idorder;
        }
        public ActionResult approveWithdraws(int id = 0)
        {
            if (id > 0)
            {
                var od = new LKVService.Transaction();
                var kq = od.updateConfirmWithdraw(id);
                if(kq == true)
                    return Json(new { Status = true, Msg = "Success" });
                else
                    return Json(new { Status = false, Msg = "Status invaild" });
            }
            else
                return Json(new { Status = false, Msg = "Error" });
        }
        public ActionResult checkTimerPayOrder(string Id_Order = "")
        {
            if (String.IsNullOrEmpty(Id_Order))
                return Json(new { Status = false, Result = "", Msg = "Order not found" });
            var od = new LKVService.OrderService();
            var order = od.findOrderbyIDOrder(Id_Order);
            if(order == null)
                return Json(new { Status = false, Result = "", Msg = "Order not found" });
            var timer = DateTime.Now.Subtract(order.Date.Value).TotalHours;
            // Sau khi kich hoat pin tren 2 ngay moi cho di
            if(timer >= 48)
                return Json(new { Status = true, Result = "", Msg = "" });
            else
                return Json(new { Status = false, Result = "", Msg = " This action take effect only after 48 hours" });
        }
        public ActionResult loadProvideOrder(int orderId = 0)
        {
            if (orderId == 0)
                return Json(new { Status = false, Result = "", Msg = "Empty Order" });
            var od = new LKVService.OrderService();
            var db = new LKVService.User();
            var order = od.FindOrderbyId(orderId);
            if(order == null)
                return Json(new { Status = false, Result = "", Msg = "Order not found" });
            var lst = od.getListProvideOrderByOrderId(orderId).ToList();
            return Json(new { Status = true, Result = lst, Msg = "Order not found" });
        }
        public ActionResult loadProvideHelp(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "Empty user" });
            var od = new LKVService.OrderService();
            var db = new LKVService.User();
            var user = db.findUserById(userId);
            if (user == null)
                return Json(new { Status = false, Result = "", Msg = "user not found" });
            var lst = od.getListProvideHelpByUserId(userId);
            return Json(new { Status = true, Result = lst, Msg = "user not found" });
        }
        public ActionResult getListRoomCodeByUserRecieve(int userRecieve = 0)
        { 
            if(userRecieve == 0)
                return Json(new { Status = false, Result = "", Msg = "" });
            var od = new LKVService.OrderService();
            var lst = od.getListRoomCodeByUserRecieve(userRecieve).Select(s => new
            { 
                Id = s.Id,
                RoomCode = s.RoomCode1,
                CreateDate = s.CreateDate != null ? s.CreateDate.Value.ToString("dd/MM/yyyy") : null,
                Status = s.Status == null ? false : s.Status.Value
            }).OrderByDescending(w => w.CreateDate).ToList();
            return Json(new { Status = true, Result = lst, Msg = "" });
        }
        public ActionResult showProvideOrderRecieve(string roomCode = "", int userRecieveId = 0)
        {
            if (String.IsNullOrEmpty(roomCode) || userRecieveId == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            var od = new LKVService.OrderService();
            var db = new LKVService.User();
            var room = od.findRoomCodeByCode(roomCode);
            if (room == null)
                return Json(new { Status = false, Result = "", Msg = "Room not found" });
            var user = db.findUserById(userRecieveId);
            if(user == null)
                return Json(new { Status = false, Result = "", Msg = "User Recieve not found" });
            var lst = od.getListProvideOrderByUserRecieve(roomCode, userRecieveId).ToList();
            return Json(new { Status = true, Result = lst, Msg = "" });
        }
        public ActionResult approveProvideOrder(int provideOrderId = 0, string roomCode = "")
        {
            if (provideOrderId == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            if(String.IsNullOrEmpty(roomCode))
                return Json(new { Status = false, Result = "", Msg = "No data" });
            var od = new LKVService.OrderService();
            var pOd = od.findProvideOrderById(provideOrderId);
            if(pOd == null)
                return Json(new { Status = false, Result = "", Msg = "Provide Order not found" });
            var room = od.findRoomCodeByCode(roomCode);
            if(room == null)
                return Json(new { Status = false, Result = "", Msg = "Room not found" });
            var order = od.FindOrderbyId(pOd.OrderId);
            if(order == null)
                return Json(new { Status = false, Result = "", Msg = "Order not found" });
            var kq = od.updateStatusProvideOrder(provideOrderId, 2);
            if(kq == false)
                return Json(new { Status = false, Result = "", Msg = "Provide Order does not update" });
            var isCheck = od.checkActiveOrderByAllProvideOrder(provideOrderId);
            if (isCheck == true)
            {
                // Active cho Order
                var check =  od.activeOrder(order.ID);
                if (check == true)
                { 
                  //add waitingRecieveRoom
                    od.addWaitingReceivedRoom(order.UserId.Value);
                  // doi status cho RoomCode 
                    od.checkUpdateStatusRoomCode(room.Id);
                }
            }
            return Json(new { Status = true, Result = "", Msg = "Success" });
        }
        public ActionResult approveProvideOrder2(int provideOrderId = 0, string roomCode = "")
        {
            if (provideOrderId == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            if (String.IsNullOrEmpty(roomCode))
                return Json(new { Status = false, Result = "", Msg = "No data" });
            var od = new LKVService.OrderService();
            var us = new LKVService.User();
            var pOd = od.findProvideOrderById(provideOrderId);
            if (pOd == null)
                return Json(new { Status = false, Result = "", Msg = "Provide Order not found" });
            var room = od.findRoomCodeByCode(roomCode);
            if (room == null)
                return Json(new { Status = false, Result = "", Msg = "Room not found" });
            var order = od.FindOrderbyId(pOd.OrderId);
            if (order == null)
                return Json(new { Status = false, Result = "", Msg = "Order not found" });
            var userGet = us.findUserById(Convert.ToInt32(pOd.UserIdGet));
            var userGive = us.findUserById(Convert.ToInt32(pOd.UserIdGive));
            if (userGet != null && userGive!=null)
            {
                if (!String.IsNullOrEmpty(userGet.EMAIL))
                {
                    MailHelper.SendMail(userGet.EMAIL, "Notication", "User "+userGive.UserName+" sent to you "+pOd.Amount+"VND please login to confirm");
                }
            }
            var kq = od.updateStatusProvideOrder(provideOrderId, 1);
            if (kq == false)
                return Json(new { Status = false, Result = "", Msg = "Provide Order does not update" });
            var isCheck = od.checkActiveOrderByAllProvideOrder(provideOrderId);
            if (isCheck == true)
            {
                // Active cho Order
                var check = od.activeOrder(order.ID);
                if (check == true)
                {
                    //add waitingRecieveRoom
                    od.addWaitingReceivedRoom(order.UserId.Value);
                    // doi status cho RoomCode 
                    od.checkUpdateStatusRoomCode(room.Id);
                }
            }
            return Json(new { Status = true, Result = "", Msg = "Success" });
        }
        public double BitcointoUSD(double bitcoin)
        {
            using (var webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString("https://blockchain.info/ticker");
                var rb = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
                if (bitcoin > 1)
                {
                    return Convert.ToDouble(rb.USD.last) * bitcoin;
                }
                return Convert.ToDouble(rb.USD.last);
            }
        }
        public ActionResult getBankList()
        {
            var db = new LKVService.OrderService();
            var list = db.getListBank();
            return Json(new { Status = true, Result = list, Msg = "Success" });
        }
        //lay list PH
        public ActionResult getListPH(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });         
            var ls = transaction.getListPH(userId);
            if(ls.Count == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            else
                return Json(new { Status = true, Result = ls, Msg = "" });
        }
        //lấy list GH
        public ActionResult getListGH(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            var ls = transaction.getListGH(userId);
            if (ls.Count == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            else
                return Json(new { Status = true, Result = ls, Msg = "" });
        }
        //lấy list Withdraw
        public ActionResult getListWd(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            var ls = transaction.getListWd(userId);
            if (ls.Count == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            else
                return Json(new { Status = true, Result = ls, Msg = "" });
        }
        //lấy ví cộng đồng
        public ActionResult getWalletPublic()
        {

            var wl = transaction.getWalletPublic();
            return Json(new { Status = true, Result = wl, Msg = "" });
        }
        //lấy số lượng PH
        public ActionResult countPH(int userId= 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            var ls = transaction.getListPH(userId);
                return Json(new { Status = true, Result = ls.Count, Msg = "" });
        }
        //lấy số lượng GH
        public ActionResult countGH(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            var ls = transaction.getListGH(userId);
            return Json(new { Status = true, Result = ls.Count, Msg = "" });
        }
        //Hàm lấy 2 wallet
        public ActionResult getWallet(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            double risk = 0;
            double profit = 0;
            risk = transaction.getWalletDetail(userId, 1) != null ? transaction.getWalletDetail(userId, 1).Balance : 0;
            profit = transaction.getWalletDetail(userId, 2) != null ? transaction.getWalletDetail(userId, 2).Balance : 0;
            return Json(new { Status = true, risk = risk, profit = profit, Msg = "" });
        }
        //cập nhất TransferOrder và check hoàn thành PH + bonus 3%
        public ActionResult confirmTransferOrder(int transId = 0, int Status = 0)
        {

            if(Status == 0)
                return Json(new { Status = false, Result = "", Msg = "Current status is New" });
            var trans = transaction.findTransferOrderById(transId);
            if(trans == null)
                return Json(new { Status = false, Result = "", Msg = "Transfer Order not found" });
            //Confirm
            if (Status == 2)
            {
                var kq = transaction.confirmTransferOrder(transId, Status);
                if(kq == true)
                {
                    var checkPH = transaction.confirmPH(trans.Ph_Id.Value);
                    if (checkPH == true)
                    {
                        var Id_Order = "OD" + DateTime.Now.ToString("dd.MM.yyyy") + DateTime.Now.Ticks;
                        //Thêm order để tính hoa hồng
                        var od = new LKVService.OrderService();
                        od.addOrder(0, trans.UserPH.Value, 4500000, 1, Id_Order, DateTime.Now, true, true, 1, 0, "", 1);
                        transaction.bonusCompletePHEarly(trans.Ph_Id.Value);                       
                    }
                    transaction.confirmGH(trans.Gh_Id.Value);
                    return Json(new { Status = true, Result = "", Msg = "Success" });
                }
                else
                    return Json(new { Status = false, Result = "", Msg = "Fail ! please try agian." });
            }
            else
                return Json(new { Status = false, Result = "", Msg = "Parameter wrong ! please try agian." });

        }
        //lấy Transfer Order
        public ActionResult findTransferOrderById(int transId = 0)
        {
            var trans = transaction.findTransferOrderById(transId);
            if (trans == null)
                return Json(new { Status = false, Result = "", Msg = "Transfer Order not found" });
            else
                return Json(new { Status = true, Result = trans, Msg = "" });
        }
        //Tạo BadReport
        public ActionResult createBadReport(int transId = 0, int type = 0, string desc = "",int actionType = 0)
        {
            var kq = transaction.createBadReport(transId, type, desc, actionType);
            if(kq.Equals("***"))
            {
                return Json(new { Status = true, Result = "", Msg = "Success" });
            }
            else
                return Json(new { Status = false, Result = "", Msg = kq });
        }
        //Hàm tạo confirm transer PH
        [HttpPost]
        public ActionResult confirmTransferPH(int transId = 0,string desc = "")
        {
            try
            {
                string fileName = "";
                foreach (string file in Request.Files)
                {
                    var fileContent = Request.Files[file];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        var stream = fileContent.InputStream;
                        // and optionally write the file to disk
                        fileName = DateTime.Now.Second + fileContent.FileName;
                        var path = Path.Combine(Server.MapPath("~/Images"), fileName);
                        using (var fileStream = System.IO.File.Create(path))
                        {
                            stream.CopyTo(fileStream);
                        }
                        stream.Close();
                    }
                }
                var kq = transaction.createConfirmTransferPH(transId, "Images/" + fileName, desc);
                if(kq)
                    return Json(new { Status = true, Result = "", Msg = "Success" });
                else
                    return Json(new { Status = false, Result = "", Msg = kq });
            }
            catch (Exception ex)
            {
                return Json(new { Status = false, Result = "", Msg = ex.ToString() });
            }

        }
        //Hàm lấy confirm transer PH
        public ActionResult getConfirmTransferPH(int transId = 0)
        {
            var kq = transaction.findConfirmTransferPH(transId);
            return Json(new { Status = true, Result = kq, Msg = "Success" });
        }
        //Hàm lấy danh sách hoa hồng theo user
        public ActionResult getListProfit(int userId = 0)
        {
            var ls = pf.profitMonth(null, userId, null);
            return Json(new { Status = true, Result = ls, Msg = "Success" });
        }
        // Hàm tạo Withdraw
        public ActionResult createWithdraw(int userPull = 0,double amount = 0)
        {
            if (userPull == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            if (amount == 0)
                return Json(new { Status = false, Result = "", Msg = "Amount must greater 0" });
            var wl = transaction.getWalletDetail(userPull, 2);
            if (wl == null)
                return Json(new { Status = false, Result = "", Msg = "Wallet does not exists" });
            if(wl.Balance >= amount)
            {
                var kq = transaction.createGHManual(userPull,1);
                if(kq.Equals("***"))
                    return Json(new { Status = true, Result = "", Msg = "Success" });
                else
                    return Json(new { Status = true, Result = "", Msg = "Fail" });
            }
            return Json(new { Status = false, Result = "", Msg = "" });
        }
        // Hàm lấy wallet theo wallet Id
        public ActionResult getWalletById(int userId = 0, int walletId = 0)
        {
            if(userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            if(walletId == 0)
                return Json(new { Status = false, Result = "", Msg = "Invaild wallet" });
            var wl = transaction.getWalletDetail(userId, walletId);
            if(wl == null)
                return Json(new { Status = false, Result = "", Msg = "Wallet does not exists" });
            else
                return Json(new { Status = true, Result = wl, Msg = "Success" });
        }
    }

    public class OrderView
    {
        public string Id { get; set; }
        public string BuyDate { get; set; }
        public double Price { get; set; }
        public double Profit { get; set; }
        public double Remain { get; set; }
        public List<LKVService.HistoryProfitPackDetail> History { get; set; } 
    }
    public class DetailPackView
    {
        public string Name { get; set; }
        public string Total { get; set; }
    }
    public class CashOutView
    {
        public int Id { get; set; }
        public int? UserId { get; set; }
        public int? WalletId { get; set; }
        public string CreateDate { get; set; }
        public string Code { get; set; }
        public double? Amount { get; set; }
        public int? Payment_Method { get; set; }
        public string Status { get; set; }
        public int From_User { get; set; }
        public string From_UserName { get; set; }
        public bool IsConfirm { get; set; }
    }
    public class PackageView 
    {
        public string Name { get; set; }
        public double Amount { get; set; }
    }

}
